import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw, NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import Layout from '@/layout/index.vue'
import { useMenuStore } from '@/stores/menu'

// 常量定义
const LOGIN_PATH = '/login'
const HOME_PATH = '/'

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: LOGIN_PATH,
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: HOME_PATH,
    component: Layout,
    children: [],  // 子路由将由后端返回的菜单动态生成
    meta: {
      requiresAuth: true
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 获取token工具函数
const getToken = (): string | null => localStorage.getItem('token')

// 重定向到登录页
const redirectToLogin = (to: RouteLocationNormalized): ReturnType<NavigationGuardNext> => {
  return {
    path: LOGIN_PATH,
    query: { redirect: to.fullPath }
  }
}

// 路由守卫
router.beforeEach(async (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) => {
  const token = getToken()
  const menuStore = useMenuStore()

  try {
    // 处理已登录状态
    if (token) {
      if (to.path === LOGIN_PATH) {
        return next(HOME_PATH)
      }

      if (!menuStore.routesAddedData()) {
        await menuStore.getMenus()
        return next({ ...to, replace: true })
      }

      return next()
    }

    // 处理未登录状态
    if (to.meta.requiresAuth) {
      return next(redirectToLogin(to))
    }

    return next()
  } catch (error) {
    console.error('路由守卫发生错误:', error)
    return next(redirectToLogin(to))
  }
})

export default router 